<?php
/**
 * Created by PhpStorm.
 * User: xiaotao
 * Date: 18-5-12
 * Time: 下午5:42
 *
 * 用户登录管理
 *
 */

namespace app\manage\controller;

use app\common\model\Rule;
use app\common\model\User;
use app\common\model\UserGroup;
use think\facade\Cache;
use think\facade\Request;

class Login
{
    /**
     * 用户登录
     * @return \think\response\Json
     */
    public function index() {
        // 输入有效性
        $error = [];
        if (!Request::has('username', 'post', true)) {
            $error[] = "用户名不能为空";
        } else {
            $username = Request::post('username');
        }
        if (!Request::has('password', 'post', true)) {
            $error[] = "密码不能为空";
        } else {
            $password = Request::post('password');
            $password = md5($password);
        }
        if ($error) {
            return $this->result_json(implode(',', $error), 201);
        }

        // 查找用户信息
        $user = User::where('username',$username)->field(['id', 'password', 'group_id', 'status'])->find();
        if (!$user) {
            return $this->result_json( '用户不存在', 202);
        }
        if ($user->password !== $password) {
            return $this->result_json( '密码错误', 203);
        }
        if ($user->status === -1) {
            return $this->result_json( '帐号被锁定，请联系管理员', 204);
        }

        // Cache
        $token = md5($user->id . ' ' . $username);
        $data = [
            'uname'     => $username,
            'uid'       => $user->id,
            'group'     => $user->group_id
        ];
        Cache::set($token, $data, 3600 * 8);

        // 登录成功
        return $this->result_json('success', 0, ['token' => $token]);
    }


    /**
     * 用户登出
     * @return mixed
     */
    public function logout() {
        $token = Request::param('token');
        // 清空Token
        Cache::rm($token);
        return $this->result_json('logout success', 0);
    }

    // 其他登录方式，如微信？

    /**
     * 获取用户基本信息和权限列表
     * @return \think\response\Json
     */
    public function user() {
        // 根据token判断是否已经登录
        $token = Request::param('token');

        // 利用缓存进行权限验证
        if (!$token && strlen($token) !== 32) {
            return $this->result_json('缺少Token', 401, null);
        }

        $cache = Cache::get($token);
        if ($cache === false) {
            return $this->result_json('用户登录已过期，请重新登录', 401, null);
        }

        $user = User::field(['name', 'avatar'])->find($cache['uid']);
        $rules = $this->get_rule($token);

        $data = [
            'rules' => $rules ?: ['home'],
            'token' => $token,
            'introduction' => $user->name,
            'avatar' => $user->avatar,
            'name' => $cache['uname']
        ];
        return $this->result_json(null, 0,$data);
    }

    /**
     * 错误返回
     * @param string $message
     * @param int $code
     * @param int $http_code
     * @return \think\response\Json
     */
    protected function result_json($message = '未知错误', $code = 105, $data = null, $http_code = 200) {
        $response = [
            'code'    => $code
        ];
        if ($message) $response['message'] = $message;
        if ($data) $response['data'] = $data;

        return json($response, $http_code);
    }


    /**
     * 从数据库获取对应用户组的权限
     * @param $group_id
     * @param $token
     * @return array
     */
    private function get_rule($token) {
        // 先超找cache
        // rule in group.auth
        $cache = Cache::get($token);
        $group_id = $cache['group'];
        if (isset($cache['routers']) && $cache['routers']) return $cache['routers'];

        // 不存在再从数据库获取
        $routers = [];
        $rules   = [];

        $map = [];
        if ($group_id !== 0) {
            $authIds = UserGroup::where('id', $group_id)->value('auth', null);
            if ($authIds) $map[] = ['id', 'in', $authIds];
        }
        $map[] = ['status', '=', 1];
        $list =Rule::where($map)->field(['route', 'rule'])->select();

        // 超级管理员配置权限
        if ($group_id === 0 && $cache['group'] === 0){
            $routers[] = 'rule';
        }
        if (!$list) return $routers;


        foreach ($list as $rule) {
            if ($rule->route)
                $routers = array_merge($routers, explode(',', $rule->route));
            if ($rule->rule)
                $rules = array_merge($rules, explode(',', $rule->rule));
        }
        // 写入缓存
        $cache['routers']   = $routers;
        $cache['rules']     = $rules;
        Cache::set($token, $cache, 3600 * 8);
        return $routers;
    }
}